package com.yao.mall.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.yao.mall.common.ErrorCode;
import com.yao.mall.constant.OssConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author jiahua.yao
 * @version 1.0
 * @description 阿里云OSS服务配置文件
 * @date 2024/3/1 22:24
 */
public class AliyunOSSConfig {
    private static final String accessKeyId = OssConstant.OSS_ACCESS_KEY_ID_IM;
    private static final String accessKeySecret = OssConstant.OSS_ACCESS_KEY_SECRET_IM;
    private static final String endpoint = OssConstant.OSS_END_POINT_IM;
    private static final String bucket = OssConstant.OSS_BUCKET_IM;

    private static final Logger logger = LoggerFactory.getLogger(AliyunOSSConfig.class);

    public static String OSSUploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream fileInputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String dateStr = format.format(new Date());
            String fileName = dateStr + "/" + new Date().getTime() + "-" + originalFilename;
            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称
            //第三个参数  上传文件输入流
            PutObjectResult result = ossClient.putObject(bucket, fileName, fileInputStream);
            String url = "https://" + bucket + "." + endpoint + "/" + fileName;
            if (null != result) {
                logger.info("==========>OSS文件上传成功,OSS地址：" + url);
                return url;
            }
        } catch (Exception oe) {
            logger.error(oe.getMessage());
        } finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

    public static Boolean OSSDeleteFile(String url) {
        if (url == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //url切割获取图片名
        String[] split = url.split("com/");
        //https://yao-mall-pic.oss-cn-beijing.aliyuncs.com/2024-03-19/1710851840382-8587475.jpg
        //需截取成2024-03-19/1710851840382-8587475.jpg
        String fileName = StringUtils.trim(split[split.length-1]);
        // 创建OSSClient实例。可以选择配置在系统中，但这里选择配置在yml文件中
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if(!ossClient.doesObjectExist(bucket, fileName)){
            throw new BusinessException(ErrorCode.NULL_ERROR,"文件不存在");
        }
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucket, fileName);
        } catch (OSSException oe) {
            logger.info("==========>OSS文件删除失败,原因：" + oe);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, oe.getErrorMessage());
        } finally {
            ossClient.shutdown();
        }
        return true;
    }
}
